<template>
    <div class="app-container">
        <el-card>
            <el-page-header @back="goBack">
                <template #content>
                    <div class="flex items-center" style="display:flex; justify-content:space-between;">
                        <div style="display: flex; align-items: center;">
                            <div>
                                {{ route.query.readonly ? '查看废料信息' : route.query.id ? '编辑废料信息' : '新增废料' }}
                            </div>
                            <el-tag v-if="route.query.code"  style="margin-left: 10px;">{{ route.query.code
                            }}</el-tag>
                            <!-- :type="tagType" -->
                        </div>
                    </div>
                </template>
                <template #extra>
                    <div>
                        <el-button v-if="!readonly" class="button" type="primary" @click="handleSubmit"> 保 存
                        </el-button>
                    </div>
                </template>
            </el-page-header>
        </el-card>
        <el-card style="margin-top: 10px;">
            <el-collapse v-model="activeNames">
                <el-collapse-item disabled  title="基本信息" name="1">
                    <template #title>
                        <el-icon style="color: #4479F6;">
                            <Position />
                        </el-icon> <span class="title">基本信息</span>
                    </template>
                    <div>
                        <el-form :model="form" :rules="rules" :disabled="readonly" ref="handleRef" label-width="130px">
                            <el-row :gutter="20">
                                <el-col :span="8">
                                    <el-form-item label="处理日期" prop="handleDate">
                                        <el-date-picker v-model="form.handleDate" style="width: 100%;"
                                            format="YYYY-MM-DD HH:mm:ss" value-format="YYYY-MM-DD HH:mm:ss"
                                            type="datetime" />
                                    </el-form-item>
                                </el-col>
                                <el-col :span="8">
                                    <el-form-item label="处理单位" prop="handleDept">
                                        <el-input v-model="form.handleDept" @click="visibleMachine = true"
                                            placeholder="请输入处理单位" style="width: 100%;" />

                                    </el-form-item>
                                </el-col>
                                <el-col :span="8">
                                    <el-form-item label="总金额">

                                        <el-input v-model="form.amountSum" type="number" maxlength="30" disabled
                                            style="width: 100%;" />
                                    </el-form-item>
                                </el-col>
                                <el-col :span="8">
                                    <el-form-item label="经办人" prop="operator">
                                        <el-input v-model="form.operator" maxlength="30" style="width: 100%;" />
                                    </el-form-item>
                                </el-col>
                                <el-col :span="8">
                                    <el-form-item label="创建人" prop="createBy">
                                        <el-input v-model="form.createBy" disabled maxlength="30" style="width: 100%;" />
                                    </el-form-item>
                                </el-col>
                                <el-col :span="8">
                                    <el-form-item label="创建时间" prop="createTime">
                                        <el-input v-model="form.createTime" disabled maxlength="30" style="width: 100%;" />
                                    </el-form-item>
                                </el-col>
                            </el-row>
                            <el-row :gutter="20">
                                <el-col :span="24">
                                    <el-form-item label="备注">
                                        <el-input v-model="form.remark" type="textarea" placeholder="请输入内容"
                                            style="width: 100%;"></el-input>
                                    </el-form-item>
                                </el-col>
                            </el-row>
                        </el-form>
                    </div>
                </el-collapse-item>
            </el-collapse>

            <el-collapse v-model="activeNames">
                <el-collapse-item disabled  title="基本信息" name="1">
                    <template #title>
                        <el-icon style="color: #4479F6;">
                            <Position />
                        </el-icon> <span class="title">处置明细</span>
                    </template>
                    <div>
                        <el-button style="margin-bottom: 5px;" :disabled="readonly" type="primary" size="small" plain
                            icon="Plus" @click="handleChoice">新增</el-button>

                        <el-table :data="mesWasteDetailList" border style="width: 100%" :header-cell-class-name="must">
                            <el-table-column type="index" label="序号" width="60" align="center" />
                            <el-table-column prop="name" label="废品名称" align="center">
                                <template #default='{ row }'>
                                    <el-select v-model="row.name" clearable :disabled="readonly" placeholder="选择废品名称">
                                        <el-option v-for="item in waste_name" :key="item.value" :label="item.label"
                                            :value="item.value" />
                                    </el-select>
                                    <!-- <el-input v-model="row.name" :disabled="readonly"></el-input> -->
                                </template>
                            </el-table-column>
                            <el-table-column prop="specs" label="规格型号" align="center">
                                <template #default='{ row }'>
                                    <el-input v-model="row.specs" :disabled="readonly"></el-input>
                                </template>
                            </el-table-column>
                            <el-table-column prop="unit" label="单位" align="center">

                                <template #default="{ row }">
                                    <el-select v-model="row.unit" clearable :disabled="readonly" placeholder="选择单位">
                                        <el-option v-for="item in mes_scrap_unit" :key="item.value" :label="item.label"
                                            :value="item.value" />
                                    </el-select>
                                </template>
                            </el-table-column>

                            <el-table-column prop="weightTare" label="皮重/kg" align="center">
                                <template #default='{ row }'>

                                    <el-input v-model="row.weightTare" :disabled="readonly" @change="computeWeight(row)"
                                        type="number"></el-input>

                                </template>
                            </el-table-column>
                            <el-table-column prop="weightGross" label="毛重/kg" align="center">
                                <template #default='{ row }'>

                                    <el-input v-model="row.weightGross" :disabled="readonly" @change="computeWeight(row)"
                                        type="number"></el-input>

                                </template>
                            </el-table-column>
                            <el-table-column prop="quantity" label="数量" align="center">
                                <template #default='{ row }'>
                                    <el-input v-model="row.quantity" :disabled="readonly" @change="computerPrice(row)"
                                        type="number"></el-input>
                                </template>
                            </el-table-column>

                            <el-table-column prop="weightNet" label="净重/kg" align="center">
                                <template #default='{ row }'>
                                    <el-input v-model="row.weightNet" type="number" disabled></el-input>
                                </template>
                            </el-table-column>
                            <el-table-column prop="price" label="单价" align="center">
                                <template #default='{ row }'>

                                    <el-input v-model="row.price" :disabled="readonly" @change="computerPrice(row)"
                                        type="number"></el-input>

                                </template>
                            </el-table-column>
                            <el-table-column prop="amount" label="金额" align="center">
                                <template #default='{ row }'>

                                    <el-input v-model="row.amount" disabled></el-input>

                                </template>
                            </el-table-column>
                            <el-table-column prop="weigher" label="过磅人" align="center">
                                <template #default="{ row }">
                                    <el-select v-model="row.weigher" clearable :disabled="readonly" placeholder="选择过磅人">
                                        <el-option label="王振武" value="22"></el-option>
                                        <el-option label="刘莉" value="9"></el-option>
                                        <el-option label="陈敏" value="13"></el-option>
                                    </el-select>
                                </template>
                            </el-table-column>
                            <el-table-column prop="remark" label="备注" align="center">
                                <template #default='{ row }'>
                                    <el-input v-model="row.remark" :disabled="readonly"></el-input>
                                </template>
                            </el-table-column>
                            <el-table-column fixed="right" label="操作" align="center">
                                <template #default="scope">
                                    <el-button link type="primary" :disabled="readonly" size="small"
                                        @click="handleDel(scope.row)">删除</el-button>
                                </template>
                            </el-table-column>
                        </el-table>

                    </div>
                </el-collapse-item>
            </el-collapse>
        </el-card>

        <customerDialog :visible="visibleMachine" @changeUpdate="changeUserData" @cancel="() => { visibleMachine = false }">
        </customerDialog>
    </div>
</template>

<script setup>
import { computed } from 'vue';
import customerDialog from '@/components/SearchCustomer'
import useTagsViewStore from '@/store/modules/tagsView'
const tagsViewStore = useTagsViewStore()
import { getWaste, addWaste, updateWaste } from '@/api/scrap/handle.js'
const { proxy } = getCurrentInstance();
const {waste_name, mes_care_plantype, mes_people_status, mes_scrap_unit } = proxy.useDict("waste_name",'mes_care_plantype', 'mes_people_status', 'mes_scrap_unit');
import { ElMessage, ElMessageBox } from 'element-plus'
import useUserStore from '@/store/modules/user'
const router = useRouter();
const route = useRoute();
const activeNames = ['1']
const handleRef = ref(null)



const mesWasteDetailList = ref([])
const readonly = ref(false)

const visibleMachine = ref(false)
const data = reactive({

    form: {},
    rules: {
        handleDept: [{ required: true, message: "处理单位不能为空", trigger: "change" }],
        handleDate: [{ required: true, message: "处理日期不能为空", trigger: "blur" },],
        amountSum: [{ required: true, message: "总金额不能为空", trigger: ["blur", "change"] }],
        operator: [{ required: true, message: "经办人不能为空", trigger: "blur" },],
        operator: [{ required: true, message: "经办人不能为空", trigger: "blur" },],
        operator: [{ required: true, message: "经办人不能为空", trigger: "blur" },],

    },
});
const { form, rules } = toRefs(data);
const userInfo = useUserStore()
const tagType = computed(() => {
    return route.query.status == 0 ? '' : 'danger';
});
readonly.value = route.query.readonly
if (route.query.id) {

    getWaste(route.query.id).then(response => {
        form.value = response.data
        mesWasteDetailList.value = response.data.mesWasteDetailList
    })
} else {
    console.log('userInfo', userInfo)
    form.value = {}
    form.value.operator = userInfo.name
    form.value.createBy = userInfo.name
    getCurrentTime()
}
function getCurrentTime() {
    const now = new Date();
    const year = now.getFullYear();
    const month = String(now.getMonth() + 1).padStart(2, '0');
    const day = String(now.getDate()).padStart(2, '0');
    const hours = String(now.getHours()).padStart(2, '0');
    const minutes = String(now.getMinutes()).padStart(2, '0');
    const seconds = String(now.getSeconds()).padStart(2, '0');
    form.value.handleDate = `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
    return form.value.createTime = `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
}
const computeWeight = (row) => {
    row.weightNet = Number(row.weightGross) - Number(row.weightTare)
    row.quantity = Number(row.weightNet)
}
const computerPrice = (row) => {
    row.amount = +(Number(row.quantity) * Number(row.price)).toFixed(4);
    sumPrice();
}
const handleChoice = () => {
    mesWasteDetailList.value.push({})
}
const must = (obj) => {
    let mustColumns = []
    mustColumns = [1];
    if (mustColumns.includes(obj.columnIndex)) {
        return 'must';
    }
}
const changeUserData = (row) => {
    console.log('row', row)
    form.value.handleDept = row.name
    form.value.handleDeptId=row.id
    visibleMachine.value = false
}

const handleDel = (row) => {
    console.log('row', row)
    const index = mesWasteDetailList.value.indexOf(row);
    if (index !== -1) {
        mesWasteDetailList.value.splice(index, 1);
        sumPrice()
    }
}
const sumPrice = () => {
    console.log('1', 1)
    form.value.amountSum = mesWasteDetailList.value.reduce((sum, item) => {
        // 将 item.amount 转换为数字，如果不能转换，则使用 0
        const amount = Number(item.amount) || 0;
        // 将当前累加和和当前项的 amount 相加，并保留四位小数
        return +(sum + amount).toFixed(4);
    }, 0);
};


//保存

const handleSubmit = async () => {
    const inconformity = mesWasteDetailList.value.find(item => {
        return !item.name
    });

    if (inconformity) {
        ElMessage({
            message: '请填写处置明细 废品名称',
            type: 'warning',
        });
        return;
    }

    handleRef.value.validate((valid) => {
        if (valid) {
            const formData = form.value;
            formData.mesWasteDetailList = mesWasteDetailList.value;
            if (formData.id) {
                updateWaste(formData).then(response => {
                    if (response.code === 200) {
                        ElMessage({
                            message: '编辑成功',
                            type: 'success',
                        });
                        goBack();
                    }
                })
            } else {
                formData.status = 0;
                addWaste(formData).then(response => {
                    if (response.code === 200) {
                        ElMessage({
                            message: '新增成功',
                            type: 'success',
                        });
                        goBack();
                    }
                })
            }
        }
    });
};

//  返回
const goBack = () => {
    tagsViewStore.delView(route)
    router.back()
}
</script>

<style lang="scss" scoped>
:deep(.el-table th.must div:before) {
    content: '*';
    color: #ff1818;
}

.margin0 {
    margin-bottom: 0 !important;
}
</style>